/*
* Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
*/
package com.hyyt.shopjsp.basic.service.imp;

import com.hyyt.shopjsp.basic.dao.BasicActorPurviewDAO;
import com.hyyt.shopjsp.basic.pojo.BasicActor;
import com.hyyt.shopjsp.basic.pojo.BasicActorPurview;
import com.hyyt.shopjsp.basic.pojo.BasicPurview;
import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicActorService;
import com.hyyt.shopjsp.basic.service.IBasicActorPurviewService;
import com.hyyt.shopjsp.basic.service.IBasicPurviewService;
import com.hyyt.shopjsp.util.redis.service.IRedisBasicService;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import org.apache.log4j.Logger;
/**
* basic_actorPurview, BASIC_功能权限关系表
 *
 * @author Robot 14-5-7 上午10:19
 */
@Service
public class BasicActorPurviewService implements IBasicActorPurviewService {
    private static  final Logger logger = Logger.getLogger(IBasicActorPurviewService.class);

    @Resource
    private BasicActorPurviewDAO basicActorPurviewDAO;
    @Resource
    private IBasicActorService basicActorService;
    @Resource
    private IBasicPurviewService basicPurviewService;

    /**
     * 保存BASIC_功能权限关系表
     *
     * @param basicActorPurview BASIC_功能权限关系表
     * @return 保存后的BASIC_功能权限关系表
     */
    @Override
    public void saveBasicActorPurview(BasicActorPurview basicActorPurview) {
        basicActorPurviewDAO.insert(basicActorPurview);
    }

    /**
     * 更新BASIC_功能权限关系表
     *
     * @param basicActorPurview BASIC_功能权限关系表
     * @return 更新后的BASIC_功能权限关系表
     */
    @Override
    public void updateBasicActorPurview(BasicActorPurview basicActorPurview) {
        basicActorPurviewDAO.update(basicActorPurview);
    }

    /**
     * 删除指定ID的BASIC_功能权限关系表
     *
     * @param id BASIC_功能权限关系表ID
     */
    @Override
    public void deleteBasicActorPurview(Integer id) {
        basicActorPurviewDAO.delete(id);
    }

    /**
     * 根据指定的多参删除角色权限关系
     * @param actorId
     * @param purviewId
     */
    @Override
    public void deleteBasicActorPurview(Integer actorId, Integer purviewId) {
        Map<String,Object> param =new HashMap<String,Object>();
        param.put("actorId",actorId);
        param.put("purviewId",purviewId);
        basicActorPurviewDAO.delete("deleteBasicActorPurview",param);
    }

    /**
     * 根据ID加载一个BASIC_功能权限关系表
     *
     * @param actorId
     * @param purviewId
     * @return BASIC_功能权限关系表
     */
    @Override
    public BasicActorPurview loadBasicActorPurview(Integer actorId,Integer purviewId) {
        Map<String,Object> param =new HashMap<String,Object>();
        param.put("actorId",actorId);
        param.put("purviewId",purviewId);
        return basicActorPurviewDAO.load("loadByActorAndPurview",param);
    }

    /**
    * 查询所有的BASIC_功能权限关系表，通常有最多取30000条记录的限制
    *
    * @return 所有的BASIC_功能权限关系表，通常有最多取30000条记录的限制
    */
    @Override
    public List<BasicActorPurview> queryAllBasicActorPurview() {
        return basicActorPurviewDAO.queryAll();
    }

    /**
     * 查询BASIC_功能权限关系表
     *
     * @param params 查询参数，为key-value形式
     * @return BASIC_功能权限关系表集合
     */
    @Override
    public List<BasicActorPurview> queryBasicActorPurview(Map<String, Object> params) {
        return basicActorPurviewDAO.query(params);
    }

    /**
     * 查询BASIC_功能权限关系表
     *
     * @param params   查询参数，没有则传null,分页参数key为“sortColumns”
     * @param startRow 起始行数（不含起始行的数据）
     * @param rowSize  要查询记录数
     * @return BASIC_功能权限关系表集合
     */
    @Override
    public List<BasicActorPurview> queryBasicActorPurview(Map<String, Object> params, int startRow, int rowSize) {
        return basicActorPurviewDAO.query(params, startRow, rowSize);
    }

    /**
     * 统计BASIC_功能权限关系表
     *
     * @param params 查询参数，没有则传null,分页参数key为“sortColumns”
     * @return 结果集记录数
     */
    @Override
    public int countBasicActorPurview(Map<String, Object> params) {
        return basicActorPurviewDAO.count(params);
    }

    /**
     * 通过用户与总权限id 获得其拥有的操作权限，功能按钮权限
     *
     * @param basicUsers
     * @param purviewId
     * @return
     */
    @Override
    public Map<String, Object> getFunctionsByActorAndPurview(BasicUsers basicUsers, Integer purviewId) {
        Map<String, Object> result = new HashMap<>();
        //绑定此权限到角色
        List<BasicActor> basicActors = basicActorService.queryAllBasicActorByUsersId(basicUsers.getUsersId());
        if (Utils.objectIsNotEmpty(basicActors) && basicActors.size() > 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("purviewId", purviewId);
            for (BasicActor actor : basicActors) {
                params.put("actorId", actor.getActorId());
                List<BasicActorPurview> list = basicActorPurviewDAO.query(params);
                if (Utils.objectIsNotEmpty(list) && list.size() > 0) {
                    for (BasicActorPurview actorPurview : list) {
                        if (Utils.objectIsNotEmpty(actorPurview.getFunctions())) {
                            String functions=actorPurview.getFunctions();
                            if(functions!=null){
                                String [] functionsArray=functions.split(",");
                                if(functionsArray!=null&&functionsArray.length>0){
                                    for(String function:functionsArray){
                                        String [] functionInfos=function.split("_");
                                        String purview_id=functionInfos[0];
                                        String functionValue=functionInfos[2];

                                        result.put(purview_id+"_"+functionValue, functionValue);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * 通过条件查询一个对象
     *
     * @param params
     * @return
     */
    @Override
    public BasicActorPurview getBasicActorPurview(Map<String, Object> params) {
        return basicActorPurviewDAO.load("query", params);
    }

    /**
     * 保存角色新的权限
     * @param purviewId 菜单权限id
     * @param actorId   角色id
     * @param functions 功能权限及菜单权限的字符集
     * @return
     */
    @Override
    public boolean saveActorPurview(Integer purviewId,Integer actorId,String functions) {
        Map<String,Object> param =new HashMap<String,Object>();
        param.put("purviewId",purviewId);
        param.put("actorId",actorId);
        BasicActorPurview third_bap=basicActorPurviewDAO.load("loadByActorAndPurview",param);
        if(Utils.objectIsNotEmpty(third_bap)){//说明中间表中已有对应的角色和权限，做updae操作
            if(Utils.objectIsNotEmpty(functions)){
                if(!functions.equals(third_bap.getFunctions())){
                    third_bap.setFunctions(functions);
                    basicActorPurviewDAO.update(third_bap);
                }
            }
        }else {//说明中间表中没有对应的角色和权限，做insert操作
            boolean isSuccess=this.saveActorPurviewForParent(purviewId,actorId);
            if(isSuccess){
                third_bap=new BasicActorPurview();
                third_bap.setActorId(actorId);
                third_bap.setPurviewId(purviewId);
                third_bap.setFunctions(functions);
                basicActorPurviewDAO.insert(third_bap);
            }
        }
        return true;
    }

    /**
     * 通过三级菜单权限获取并保存一级和二级菜单权限与对应的角色关系
     *
     * @param third_purviewId 三级权限ID
     * @param actorId
     * @return
     */
    public boolean saveActorPurviewForParent(Integer third_purviewId,Integer actorId){
        BasicPurview third_bp=basicPurviewService.loadBasicPurview(third_purviewId);
        Integer second_purviewId=third_bp.getParentId();//二级菜单权限id

        Map<String,Object> param =new HashMap<String,Object>();
        param.put("purviewId",second_purviewId);
        param.put("actorId",actorId);
        BasicActorPurview second_bap=basicActorPurviewDAO.load("loadByActorAndPurview",param);
        if(Utils.objectIsEmpty(second_bap)){//如果二级菜单权限和指定的角色没有对应关系，说明一级菜单权限肯定也没有对应关系，所以都要和指定的权限建立对应关系
            //通过二级菜单权限id获取一级菜单权限id并保存一级菜单权限和角色的对应关系
            BasicPurview sencond_bp=basicPurviewService.loadBasicPurview(second_purviewId);
            Integer first_purviewId=sencond_bp.getParentId();//一级菜单权限id
            param.clear();
            param.put("purviewId",first_purviewId);
            param.put("actorId",actorId);
            BasicActorPurview first_bap=basicActorPurviewDAO.load("loadByActorAndPurview",param);
            if(Utils.objectIsEmpty(first_bap)){//一级菜单与其对应的角色在中间表中没有的话，需要进行插入
                first_bap=new BasicActorPurview();
                first_bap.setPurviewId(first_purviewId);
                first_bap.setActorId(actorId);
                basicActorPurviewDAO.insert(first_bap);
            }
            //保存二级菜单权限和角色的关系
            second_bap=new BasicActorPurview();
            second_bap.setPurviewId(second_purviewId);
            second_bap.setActorId(actorId);
            basicActorPurviewDAO.insert(second_bap);
        }
        return true;
    }

}